import 'package:flutter_app_demo/model/account.dart';
import 'package:flutter_app_demo/net/http_agent.dart';
import 'package:json_annotation/json_annotation.dart';

import 'api_exception.dart';

part 'base_data.g.dart';

///
/// Created by wangliang on 2024/8/8

@JsonSerializable()
class BaseData {
  @JsonKey(name: "code")
  final int code;
  @JsonKey(name: "msg")
  final String? msg;
  Map<String, dynamic>? data;

  BaseData({required this.code, required this.msg, required this.data});

  factory BaseData.fromJson(Map<String, dynamic> json) => _$BaseDataFromJson(json);

  Map<String, dynamic> toJson() => _$BaseDataToJson(this);
}

typedef JsonFactory<T> = T Function(Map<String, dynamic> json);

class ModelConvertUtils {
  static final Map<Type, JsonFactory> _factories = {};

  static void registerFactory<T>(JsonFactory<T> factory) {
    _factories[T] = factory;
  }

  // 需要解析的实体类需要注册一下
  static void init() {
    ModelConvertUtils.registerFactory<Account>((json) => Account.fromJson(json));
  }

  static T fromJson<T>(Map<String, dynamic> json) {
    final factory = _factories[T];
    if (factory != null) {
      return factory(json);
    } else {
      throw ApiException(
        code: HttpAgent.defaultServerErrorCode,
        message: "Factory for type $T not registered, pls register at ModelConvertUtils.init()",
      );
    }
  }
}
